import {useEffect, useState} from 'react';
import axios from "axios";

function usePublish(type){

    const {username} = JSON.parse(localStorage.getItem('token'))
    const [dataSource,setDataSource]=useState([])

    useEffect(()=>{
        axios.get(`/news?author=${username}&publishState=${type}&_expand=category`).then(
            res=>{
                const list=res.data
                setDataSource(list)
            }
        )
    },[username,type])

    const publishNews=(id)=>{
        setDataSource(dataSource.filter(data=>data.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:2,
            publishTime:Date.now()
        })
    }

    const sunsetNews=(id)=>{
        setDataSource(dataSource.filter(data=>data.id!==id))
        axios.patch(`/news/${id}`,{
            publishState:3
        })
    }

    const deleteNews=(id)=>{
        setDataSource(dataSource.filter(data=>data.id!==id))
        axios.delete(`/news/${id}`)
    }

    return {
        dataSource,
        publishNews,
        sunsetNews,
        deleteNews
    }
}

export default usePublish;